<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org ">
<head>
    <meta charset="UTF-8">
    <title>学生列表</title>
    <link rel="stylesheet" href="/css/layui.css" >
    <link rel="stylesheet" href="/css/container.css">
</head>
<body>

<div class="container tablestudent">
    <div class="layui-row" style="margin-bottom: 15px;">
        <div class="layui-col-xs12">
            <form class="layui-form layui-form-pane">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">姓名</label>
                        <div class="layui-input-inline">
                            <input type="text" id="searchName" name="name" placeholder="请输入姓名" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">专业</label>
                        <div class="layui-input-inline">
                            <select id="searchMajor" name="major">
                                <option value="">请选择专业</option>
                                <option value="计算机科学与技术">计算机科学与技术</option>
                                <option value="软件工程">软件工程</option>
                                <option value="人工智能">人工智能</option>
                                <option value="信息安全">信息安全</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">性别</label>
                        <div class="layui-input-inline">
                            <select id="searchGender" name="gender">
                                <option value="">请选择性别</option>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="button" class="layui-btn" id="searchBtn">搜索</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
   <div class="layui-row">
       <div class="layui-col-xs12">
           <table  class="layui-table" lay-even>
               <thead>
               <tr>
                   <th>学号</th>
                   <th>姓名</th>
                   <th>性别</th>
                   <th>专业</th>
                   <th>操作</th>
               </tr>
               </thead>
               <tbody  id="studentTableBody">

               </tbody>
           </table>
       </div>
   </div>
    <div class="layui-col-xs12" style="text-align: right;">
        <button type="button"  id="addstudents" class="layui-btn layui-bg-purple">新增学生</button>
    </div>
</div>

<div class="layui-row" id="studentform" style="display: none">
    <div class="layui-col-xs12">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <label class="layui-form-label">学号</label>
                <div class="layui-input-block">
                    <input type="text" name="studentId" required lay-verify="required" placeholder="请输入学号" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" required lay-verify="required" placeholder="请输入姓名" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                    <input type="radio" name="gender" value="男" title="男">
                    <input type="radio" name="gender" value="女" title="女">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">专业</label>
                <div class="layui-input-block">
                    <select name="major" lay-verify="required">
                        <option value="">请选择专业</option>
                        <option value="计算机科学与技术">计算机科学与技术</option>
                        <option value="软件工程">软件工程</option>
                        <option value="人工智能">人工智能</option>
                        <option value="信息安全">信息安全</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">联系电话</label>
                <div class="layui-input-block">
                    <input type="tel" name="phone" lay-verify="phone" placeholder="请输入手机号" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input type="text" name="email" lay-verify="email" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="editStudentForm">保存信息</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>



    </div>
</div>

</body>
<script src="/js/layui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    // 使用 Axios 获取学生数据
    axios.get('/list')  // 替换为你的实际接口地址
        .then(function (response) {
            // 请求成功，处理返回的数据
            const students = response.data.data;
            const tableBody = document.getElementById('studentTableBody');

            // 清空当前表格内容
            tableBody.innerHTML = '';

            // 遍历学生数据并生成表格行
            students.forEach(student => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${student.studentId}</td>
                    <td>${student.name}</td>
                    <td>${student.gender}</td>
                    <td>${student.major}</td>
                    <td>
                        <div class="layui-row">
                            <div class="layui-col-xs12">
                                <button type="button" class="layui-btn layui-btn-sm edit-btn" data-id="${student.studentId}">编辑</button>
                                <button type="button" class="layui-btn layui-btn-sm layui-border-red delete-btn layui-bg-red" data-id="${student.studentId}"><span style="color:white;">删除</span></button>
                            </div>
                        </div>
                  </td>`;
                tableBody.appendChild(row);
            });
        })
        .catch(function (error) {
            console.error('获取学生数据失败:', error);
        });
</script>
<script>
<!--    弹窗逻辑-->
document.getElementById('studentTableBody').addEventListener('click', function (e) {
    // 编辑按钮
    if (e.target && e.target.classList.contains('edit-btn')) {
        const studentId = e.target.getAttribute('data-id');

        // 同时请求学生详情和专业列表
        Promise.all([
            axios.get(`/list/${studentId}`),
            axios.get('/majors') // 替换为你实际的专业接口
        ]).then(([studentRes, majorsRes]) => {
            const student = studentRes.data;
            const majors = majorsRes.data;

            layui.use(['jquery', 'form'], function () {
                const $ = layui.$;
                const form = layui.form;

                const $majorSelect = $('#studentform [name=major]');

                // 清空原有选项
                $majorSelect.empty().append('<option value="">请选择专业</option>');

                // 动态添加专业选项
                majors.forEach(major => {
                    $majorSelect.append(`<option value="${major}">${major}</option>`);
                });

                // 设置表单值
                $('#studentform [name=studentId]').val(student.studentId);
                $('#studentform [name=name]').val(student.name);

                $(`#studentform [name=gender][value='${student.gender === 'M' ? '男' : '女'}']`).prop('checked', true);

                // 设置专业选中项（会自动匹配 option 的 value）
                $majorSelect.val(student.major);

                // 重新渲染layui表单样式
                form.render('select');

                // 弹出层逻辑
                layer.open({
                    type: 1,
                    area: ['600px', '450px'],
                    title: '编辑学生信息',
                    shade: 0.6,
                    shadeClose: true,
                    maxmin: true,
                    anim: 0,
                    content: $('#studentform'),
                    success: function(layero, index) {
                        console.log('弹出层打开成功');
                    }
                });
                form.on('submit(editStudentForm)', function (data) {
                    // 获取表单数据
                    const formData = data.field;

                    // 构造要发送的数据对象
                    const studentData = {
                        studentId: formData.studentId,
                        name: formData.name,
                        gender: formData.gender === '男' ? 'M' : 'F', // 假设性别字段是 M/F
                        major: formData.major
                    };

                    // 发送 PUT 请求到后端接口
                    axios.put('/update', studentData)
                        .then(function (response) {
                            layer.msg('保存成功');
                            layer.closeAll(); // 关闭弹窗
                            location.reload(); // 刷新页面以显示最新数据（或手动更新表格）
                        })
                        .catch(function (error) {
                            layer.msg('保存失败');
                            console.error('更新失败:', error);
                        });

                    return false; // 阻止表单默认提交行为
                });
            });
        }).catch(function (error) {
            console.error('请求失败:', error);
        });
    }
    // 删除按钮逻辑
    if (e.target && e.target.classList.contains('delete-btn')) {
        const studentId = e.target.getAttribute('data-id');

        // 弹出确认框
        layer.confirm('确定要删除该学生吗？', { icon: 3, title: '提示' }, function (index) {
            // 发送 DELETE 请求
            axios.delete(`/delete/${studentId}`)
                .then(function (response) {
                    layer.msg('删除成功');
                    // 从表格中移除该行
                    e.target.closest('tr').remove();
                    layer.close(index);
                })
                .catch(function (error) {
                    layer.msg('删除失败');
                    console.error('删除失败:', error);
                });
        });
    }
});





</script>
<script>
<!--新增学生数据-->

// 新增学生按钮点击事件
document.getElementById('addstudents').addEventListener('click', function () {
    layui.use(['jquery', 'form'], function () {
        const $ = layui.$;
        const form = layui.form;

        // 清空表单内容（手动设置）
        $('#studentform input[type="text"]').val('');
        $('#studentform input[type="tel"]').val('');
        $('#studentform input[type="email"]').val('');
        $('#studentform input[type="radio"]').prop('checked', false);
        $('#studentform select').val('');
        layui.form.render(); // 重新渲染layui表单样式

        // 动态获取专业列表
        axios.get('/majors')
            .then(function (response) {
                const majors = response.data;
                const $majorSelect = $('#studentform [name=major]');

                // 清空原有选项
                $majorSelect.empty().append('<option value="">请选择专业</option>');

                // 动态添加专业选项
                majors.forEach(major => {
                    $majorSelect.append(`<option value="${major}">${major}</option>`);
                });

                // 重新渲染layui表单样式
                form.render('select');

                // 弹出层逻辑
                layer.open({
                    type: 1,
                    area: ['600px', '450px'],
                    title: '新增学生',
                    shade: 0.6,
                    shadeClose: true,
                    maxmin: true,
                    anim: 0,
                    content: $('#studentform'),
                    success: function (layero, index) {
                        console.log('弹出层打开成功');
                    }
                });

                // 表单提交事件监听
                form.on('submit(editStudentForm)', function (data) {
                    const formData = data.field;

                    // 构造要发送的数据对象
                    const studentData = {
                        studentId: formData.studentId,
                        name: formData.name,
                        gender: formData.gender === '男' ? 'M' : 'F',
                        major: formData.major,
                        phone: formData.phone || null,
                        email: formData.email || null
                    };

                    // 发送 POST 请求到后端接口
                    axios.post('/add', studentData)
                        .then(function (response) {
                            layer.msg('添加成功');
                            layer.closeAll(); // 关闭弹窗
                            location.reload(); // 刷新页面或手动更新表格
                        })
                        .catch(function (error) {
                            layer.msg('添加失败');
                            console.error('添加失败:', error);
                        });

                    return false; // 阻止表单默认提交行为
                });
            })
            .catch(function (error) {
                console.error('获取专业列表失败:', error);
            });
    });
});





</script>

<script>
<!--  搜索功能   -->
// 搜索按钮点击事件
document.getElementById('searchBtn').addEventListener('click', function () {
    // 获取搜索表单字段值
    const name = document.getElementById('searchName').value.trim();
    const major = document.getElementById('searchMajor').value;
    const gender = document.getElementById('searchGender').value;

    // 构建 student 对象
    const student = {};
    if (name) student.name = name;
    if (major) student.major = major;
    if (gender) student.gender = gender;

    // 发送 POST 请求到 /search
    axios.post('/search', student)
        .then(function (response) {
            renderStudentTable(response.data.data);
        })
        .catch(function (error) {
            console.error('搜索失败:', error);
            layer.msg('搜索失败');
        });
});
function renderStudentTable(students) {
    const tableBody = document.getElementById('studentTableBody');
    tableBody.innerHTML = ''; // 清空旧数据

    if (students.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="5" style="text-align:center;">没有找到相关学生信息</td></tr>';
        return;
    }

    students.forEach(student => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${student.studentId}</td>
            <td>${student.name}</td>
            <td>${student.gender}</td>
            <td>${student.major}</td>
            <td>
                <div class="layui-row">
                    <div class="layui-col-xs12">
                        <button type="button" class="layui-btn layui-btn-sm edit-btn" data-id="${student.studentId}">编辑</button>
                        <button type="button" class="layui-btn layui-btn-sm layui-border-red delete-btn layui-bg-red" data-id="${student.studentId}"><span style="color:white;">删除</span></button>
                    </div>
                </div>
            </td>`;
        tableBody.appendChild(row);
    });
}


document.querySelector('.layui-btn-primary').addEventListener('click', function () {
    document.getElementById('searchName').value = '';
    document.getElementById('searchMajor').value = '';
    document.getElementById('searchGender').value = '';
    layui.form.render(); // 重新渲染 select 状态

    axios.post('/search', {})
        .then(function (response) {
            renderStudentTable(response.data.data);
        });
});



</script>


</html>